package com.example.demomk.Fragment;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.demomk.Adapter.CountAdapter;
import com.example.demomk.Adapter.DetailsAdapter;
import com.example.demomk.Adapter.LocationStatsAdapter;
import com.example.demomk.R;
import com.example.demomk.Utils.StatRow;
import com.example.demomk.ViewModel.MeasurementViewModel;
import com.example.demomk.databinding.FragmentChildCountBinding;
import com.example.demomk.entity.AvgMeasurement;
import com.example.demomk.entity.LocationStats;
import com.example.demomk.entity.SizeStats;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class ChildCount extends Fragment {

    private CountAdapter adapter;
    private LocationStatsAdapter locAdapter;
    private RecyclerView recyclerView, locRecycler;
    private MeasurementViewModel viewmodel;

    private FragmentChildCountBinding binding;
    private static final String ARG_PARAM1 = "param1";

    // TODO: Rename and change types of parameters
    private static final String ARG_PARAM2 = "param2";
    private int mParam1;
    private int page;
//    private List<String> allCounts = new ArrayList<>();

    public ChildCount() {
        // Required empty public constructor
    }


    public static ChildCount newInstance(int param1,  int page) {
        ChildCount fragment = new ChildCount();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, param1);
        args.putInt(ARG_PARAM2, page);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getInt(ARG_PARAM1);
            page = getArguments().getInt(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        binding = FragmentChildCountBinding.inflate(inflater,container,false);
        return binding.getRoot();
    }
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        FragmentActivity fragmentActivity = requireActivity();
        initView(fragmentActivity);
        setupData();


    }

    private void setupData() {

        viewmodel.getAvgMeasurementById(mParam1).observe(getViewLifecycleOwner(), avgMeasurements -> {
            for (AvgMeasurement avg : avgMeasurements) {
                viewmodel.calculateStatsForAvgAsync(avg, statsList -> {
                    // 构建每行统计项
                    List<StatRow> statRows = new ArrayList<>();
                    // MAX 行
                    StatRow maxRow = new StatRow("MAX",
                            getValue(statsList, "0.5", SizeStats::getMax),
                            getValue(statsList, "1.0", SizeStats::getMax),
                            getValue(statsList, "2.0", SizeStats::getMax),
                            getValue(statsList, "3.0", SizeStats::getMax),
                            getValue(statsList, "5.0", SizeStats::getMax),
                            getValue(statsList, "10.0", SizeStats::getMax));

                    // SD 行
                    StatRow sdRow = new StatRow("SD(std Dev)",
                            getValue(statsList, "0.5", SizeStats::getSd),
                            getValue(statsList, "1.0", SizeStats::getSd),
                            getValue(statsList, "2.0", SizeStats::getSd),
                            getValue(statsList, "3.0", SizeStats::getSd),
                            getValue(statsList, "5.0", SizeStats::getSd),
                            getValue(statsList, "10.0", SizeStats::getSd));

                    // SE 行
                    StatRow seRow = new StatRow("SE(Std Error)",
                            getValue(statsList, "0.5", SizeStats::getSe),
                            getValue(statsList, "1.0", SizeStats::getSe),
                            getValue(statsList, "2.0", SizeStats::getSe),
                            getValue(statsList, "3.0", SizeStats::getSe),
                            getValue(statsList, "5.0", SizeStats::getSe),
                            getValue(statsList, "10.0", SizeStats::getSe));

                    // TotaL-AVE 行
                    StatRow avgRow = new StatRow("TotaL-AVE",
                            getValue(statsList, "0.5", SizeStats::getAvg),
                            getValue(statsList, "1.0", SizeStats::getAvg),
                            getValue(statsList, "2.0", SizeStats::getAvg),
                            getValue(statsList, "3.0", SizeStats::getAvg),
                            getValue(statsList, "5.0", SizeStats::getAvg),
                            getValue(statsList, "10.0", SizeStats::getAvg));
                    // 95%UCL
                    StatRow uclRow = new StatRow("95%UCL",0.0,0.0,0.0,0.0,0.0,0.0);
                    // MAX(LOC-AVE)
                    StatRow maxLocRow = new StatRow("MAX(LOC-AVE)",
                            getValue(statsList, "0.5", SizeStats::getMAX_LOC),
                            getValue(statsList, "1.0", SizeStats::getMAX_LOC),
                            getValue(statsList, "2.0", SizeStats::getMAX_LOC),
                            getValue(statsList, "3.0", SizeStats::getMAX_LOC),
                            getValue(statsList, "5.0", SizeStats::getMAX_LOC),
                            getValue(statsList, "10.0", SizeStats::getMAX_LOC));
                    // 报警水平(∑/#)
                    StatRow alarmRow = new StatRow("报警水平(∑/#)","-","-","-","-","-","-");
                    // 阈值(∑/#)
                    StatRow thresholdRow = new StatRow("阈值(∑/#)","-","-","-","-","-","-");

                    statRows.add(avgRow);
                    statRows.add(sdRow);
                    statRows.add(seRow);
                    statRows.add(uclRow);
                    statRows.add(maxRow);
                    statRows.add(maxLocRow);
                    statRows.add(alarmRow);
                    statRows.add(thresholdRow);


                    adapter.submitList(statRows);
                });
            }
        });


        viewmodel.getLocationStatsByAvgId(mParam1).observe(requireActivity(), locationStats -> {
            if (locationStats != null){
                locAdapter.submitList(locationStats);
            }else {
                Log.d("TAG", "setupData: null");
            }
        });

    }

    private void setLocData() {

    }

    private double getValue(List<SizeStats> statsList, String sizeName, Function<SizeStats, Double> extractor) {
        return statsList.stream()
                .filter(s -> s.getSizeName().equals(sizeName))
                .findFirst()
                .map(extractor)
                .orElse(0.0);
    }

    private void initView(FragmentActivity fragmentActivity) {
        viewmodel = new ViewModelProvider(this).get(MeasurementViewModel.class);
        recyclerView = binding.countRecycler;
        adapter = new CountAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(fragmentActivity));
//        recyclerView.addItemDecoration(new DividerItemDecoration(fragmentActivity, DividerItemDecoration.VERTICAL));

        DividerItemDecoration divider = new DividerItemDecoration(fragmentActivity, DividerItemDecoration.VERTICAL);
        int color = ContextCompat.getColor(fragmentActivity, R.color.blue); // 替换为你想要的颜色
        divider.setDrawable(new ColorDrawable(color));
        recyclerView.addItemDecoration(divider);

        recyclerView.setAdapter(adapter);

        //点位统计的列表
        locRecycler = binding.locRecycler;
        locAdapter = new LocationStatsAdapter();
        locRecycler.setLayoutManager(new LinearLayoutManager(fragmentActivity));
        locRecycler.addItemDecoration(new DividerItemDecoration(fragmentActivity, DividerItemDecoration.VERTICAL));
        locRecycler.setAdapter(locAdapter);

//        allCounts.add("TotaL-AVE");
//        allCounts.add("SD(std Dev)");
//        allCounts.add("SE(Std Error)");
//        allCounts.add("95%UCL");
//        allCounts.add("MAX");
//        allCounts.add("MAX(LOC-AVE)");

        binding.count.setText("样本数: "+page);
    }


}